import base64
import datetime
import hashlib
import os
import random
import logging

import requests

from application.constant import MODEL_TRANSLATE_INTERFACE
from application.utils.base_token import Token

logger = logging.getLogger('log')


def generate_random_id(prefix):
    """
    生成id随机数
    :author Mabin
    :param prefix: ID前缀
    :return: id随机数
    """
    time_buf = datetime.datetime.now()
    ms = time_buf.strftime('%Y%m%d%H%M%S%f')[:-2]
    return prefix + ms + str(random.randint(100000, 999999))


def get_image_url_to_base64(image_url, timeout=10):
    """
    根据图片连接，获得图片Base64
    :param str image_url:待请求的图片URL
    :param int timeout:请求超时时间（秒）
    :author Mabin
    :return:
    """
    if not image_url:
        return None

    # 请求相关连接
    response = requests.get(image_url, timeout=timeout)

    images_base64 = None
    if response.ok:
        # 图片转base64格式
        images_base64 = f"data:{response.headers['Content-Type']};base64," \
                        f"{base64.b64encode(response.content).decode('utf-8')}"

    return images_base64


def get_file_md5(file_name):
    """
    根据本地文件，计算其MD5
    :author Mabin
    :param str file_name:本地文件路径
    :return:
    """
    if not os.path.isfile(file_name):
        # 文件不存在
        return False

    temp_md5 = hashlib.md5()
    with open(file_name, 'rb') as obj:
        while True:
            data = obj.read(4096)
            if not data:
                break
            temp_md5.update(data)  # 更新md5对象

    # 返回md5对象
    return temp_md5.hexdigest()


def translation_text_content(text_content):
    """
    翻译文本内容
    :author MYL
    :param text_content:
    :return:
    """
    if not text_content:
        return {"result": True, "msg": "暂无所需翻译内容", "data": ""}
    # 组织请求信息
    request_data = {
        "token": Token.gen_token_info(),
        "model_type": "glm-4-flash",
        "translated_text": text_content,
    }

    retry_times = 0
    target_times = 3
    is_finish = False
    response_data = None
    translate_result = None
    while retry_times < target_times:
        try:
            response_res = requests.post(
                url=MODEL_TRANSLATE_INTERFACE,
                json=request_data
            )
            if response_res.status_code != 200:
                raise Exception("翻译失败")
            response_data = response_res.json()
            if response_data["code"] != 200:
                raise Exception(response_data["msg"])
            is_finish = True
            break
        except Exception as e:
            retry_times += 1
            logger.error(f"翻译接口请求失败:{e}")
    if not is_finish:
        return {"result": False, "msg": f"翻译失败{translate_result if translate_result else ''}"}

    return {"result": True, "msg": "ok!", "data": response_data["data"]}
